package connet_sever;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class FileReciver implements Runnable {

	private static final int PORT = 2000;
	private static final String URL = "127.0.0.1";
	
	private String path;
	
	public void setPath(String path) {
		this.path = path;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			Socket s = new Socket(URL,PORT);
			getFile(s);
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getFile(Socket s) throws IOException
	{
		DataInputStream inputstream = new DataInputStream(new BufferedInputStream(s.getInputStream()));
		String FilePath = path;
		int buffersize = 8192;
		byte[] buf = new byte[buffersize];
		int passedlen = 0;
		long len = 0;
		
		FilePath += inputstream.readUTF();
        DataOutputStream fileOut = new DataOutputStream(new BufferedOutputStream(new BufferedOutputStream(new FileOutputStream(FilePath))));
        len = inputstream.readLong();
		
        while (true) {
            int read = 0;
            if (inputstream != null) {
                read = inputstream.read(buf);
            }
            passedlen += read;
            if (read == -1) {
                break;
            }
            //下面进度条本为图形界面的prograssBar做的，这里如果是打文件，可能会重复打印出一些相同的百分比
            System.out.println("文件接收了" +  (passedlen * 100/ len) + "%\n");
            fileOut.write(buf, 0, read);
        }
        System.out.println("接收完成，文件存为" + FilePath + "\n");

        fileOut.close();
	}
	
}
